package ext.tianma.part.forms;

import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import wt.method.RemoteAccess;
import wt.org.WTPrincipal;
import wt.part.WTPart;
import wt.session.SessionHelper;
import wt.util.WTException;
import wt.util.WTProperties;

import com.ptc.core.components.beans.ObjectBean;
import com.ptc.core.components.forms.DefaultObjectFormProcessor;
import com.ptc.core.components.forms.FormProcessingStatus;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.components.util.FeedbackMessage;
import com.ptc.core.ui.resources.FeedbackType;
import com.ptc.netmarkets.model.NmOid;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import ext.com.iba.IBAUtil;

public class TransitFactoryProcessor extends DefaultObjectFormProcessor implements RemoteAccess, Serializable{
	private static boolean VERBOSE = false;
    private static String CLASSNAME = TransitFactoryProcessor.class.getName();
    private static final String RESOURCE = "ext.tianma.resource.ResourceRB";
    //半成品分类
    private static final String SEM_FINISHED_GOOD_TYPE = "SemiFinishedGoodType";
    //成品分类
    private static final String FINISHED_GOOD_TYPE = "FinishedGoodType";
    static
    {
        try
        {
            WTProperties wtproperties = WTProperties.getLocalProperties();
            VERBOSE = wtproperties.getProperty("ext.tianma.part.verbose", false);
        }
        catch (Throwable throwable)
        {
            throwable.printStackTrace(System.err);
            throw new ExceptionInInitializerError(throwable);
        }
    }
    @Override
	public FormResult doOperation(NmCommandBean arg0, List<ObjectBean> arg1) throws WTException {
		FormResult formresult = new FormResult();
		formresult.setStatus(FormProcessingStatus.SUCCESS);
	
		WTPrincipal curUser= SessionHelper.manager.getPrincipal();
		SessionHelper.manager.setAdministrator();

		
		NmOid nmoid = arg0.getActionOid();
		WTPart currentPart = (WTPart) nmoid.getRefObject();
//		try {
//			if(PartCommands.isObjectCheckedOut(currentPart))
//			{
//				throw new WTException("编号为    "+currentPart.getNumber()+"的部件被检出,不能转厂!");
//			}
//		} catch (WTPropertyVetoException e2) {
//			// TODO Auto-generated catch block
//			e2.printStackTrace();
//		}
//		String number = currentPart.getNumber();
//		String exitFactory = "";
//		try {
//			exitFactory = (String) IBAUtil.getIBAValue(currentPart, "partNumberEffectiveSite");
//			System.out.println("Debug  BOM转厂   已经存在的物料生效地："+exitFactory);
//		} catch (RemoteException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
//		if(null==exitFactory)
//		{
//			exitFactory = "";
//		}
//		System.out.println("Debug  BOM转厂   当前进阶的物料编号："+currentPart.getNumber());
		HttpServletRequest request = arg0.getRequest();
//		/*ArrayList factoryList =(ArrayList)arg0.getChecked().get("factory");
//		for(int i=0;i<factoryList.size();i++)
//		{
//			Object obj = factoryList.get(i);
//			System.out.println("Debug  BOM转厂   选择的生效地："+obj.toString());
//		}*/
		String[] factorys = request.getParameterValues("factory");
//		if(null == factorys||factorys.length==0)
//		{
//			throw new WTException("没有选择物料生效的请选择！");
//		}
//		String factory = "";
//		for(int i = 0;i<factorys.length;i++)
//		{
//			String temp = factorys[i];
//			if(factory.equals(""))
//			{
//				factory = temp;
//			}
//			else
//			{
//				factory = factory+","+temp;
//			}
//			//System.out.println("Debug  BOM转厂   选择的生效地："+temp);
//		}
//		System.out.println("Debug  BOM转厂   要设置的生效地："+factory);
//		try {
//			PartCommands.setEffectiveSite(currentPart, PartCommands.getConfigSpec(), factory);
//		} catch (WTPropertyVetoException e) {
//			// TODO Auto-generated catch block
//			throw new WTException(e);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			throw new WTException(e);
//		}
//		
//		for(int i = 0;i<factorys.length;i++)
//		{
//			String temp = factorys[i];
//			System.out.println("Debug  BOM转厂 当前要转的视图为："+temp);
//			if(exitFactory.contains(temp))
//			{
//				continue;
//			}
//			WTPart part=null;
//			try {
//				part=(WTPart) ViewHelper.service.newBranchForView(currentPart, temp);
//				part = (WTPart) PersistenceHelper.manager.save(part);
//				part= (WTPart)LifeCycleHelper.service.setLifeCycleState(part, State.INWORK);
//				
//				IBAUtil.forceSetIBAValue(part, "partNumberEffectiveSite", temp);
//			} catch (WTPropertyVetoException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
		
		if( TMTypeUtil.isSemiFinishedGood( currentPart ) ){
			
			if( !hasSemiFinishedAttributesFill(currentPart) ){
				throw new WTException( "半成品的“半成品分类”必须有值！" );
			}
			
		}else if( TMTypeUtil.isFinishedGood( currentPart ) ){
			
			if( !hasSemiFinishedAttributesFill(currentPart) ){
				throw new WTException( "成品的“成品分类”必须有值！" );
			}
		}
		
		try {
			TransitFactoryUtil.tansitPartAndChildrenFactory( currentPart , factorys );
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		SessionHelper.manager.setPrincipal(curUser.getName());
		FeedbackMessage feedbackmessage = new FeedbackMessage(
				FeedbackType.SUCCESS, null, "BOM转厂成功", null, new String[] {});
		formresult.addFeedbackMessage(feedbackmessage);
		return formresult;
	}
    
    
    /**
	 * 判断半成品和成品的“半成品分类”和“成品分类”属性是否有值，没有值得情况下不能转厂
	 * @param part
	 * @return
	 * @throws WTException 
	 * @throws RemoteException 
	 */
	private static boolean hasSemiFinishedAttributesFill( WTPart part ){
		boolean hasSemiFinishedAttributesFill = false;
		
		if( part == null ){
			return hasSemiFinishedAttributesFill;
		}
		try{
			
			if( TMTypeUtil.isSemiFinishedGood( part ) ){
				
				String semFinishedGoodType = (String)IBAUtil.getIBAValue( part , SEM_FINISHED_GOOD_TYPE );
				System.out.println( "Debug   semFinishedGoodType = "+semFinishedGoodType );
				if( semFinishedGoodType != null && !semFinishedGoodType.trim().isEmpty() ){
					hasSemiFinishedAttributesFill = true;
				}
				
			}else if( TMTypeUtil.isFinishedGood( part ) ){
				String finishedGoodType = (String)IBAUtil.getIBAValue( part , FINISHED_GOOD_TYPE );
				System.out.println( "Debug   finishedGoodType = " + finishedGoodType );
				if( finishedGoodType != null && !finishedGoodType.trim().isEmpty() ){
					hasSemiFinishedAttributesFill = true;
				}
			}				
		}catch (RemoteException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}		
		return hasSemiFinishedAttributesFill;
	}

}
